<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/atom.xml" title="renhao" type="application/atom+xml">






<meta name="description" content="这里是在做项目的时候考虑到注册、登录以及用户验证之间的问题而涉及的。">
<meta property="og:type" content="article">
<meta property="og:title" content="加盐，HMAC和token">
<meta property="og:url" content="https://huangrenhao.gitee.io/2019/07/25/browser-jia-yan-hmac-he-token/index.html">
<meta property="og:site_name" content="renhao">
<meta property="og:description" content="这里是在做项目的时候考虑到注册、登录以及用户验证之间的问题而涉及的。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-10-12T02:26:59.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="加盐，HMAC和token">
<meta name="twitter:description" content="这里是在做项目的时候考虑到注册、登录以及用户验证之间的问题而涉及的。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://huangrenhao.gitee.io/2019/07/25/browser-jia-yan-hmac-he-token/">





  <title>加盐，HMAC和token | renhao</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">renhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://huangrenhao.gitee.io/2019/07/25/browser-jia-yan-hmac-he-token/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="renhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="renhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">加盐，HMAC和token</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-25T16:48:59+08:00">
                2019-07-25
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/browser/" itemprop="url" rel="index">
                    <span itemprop="name">browser</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/07/25/browser-jia-yan-hmac-he-token/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/07/25/browser-jia-yan-hmac-he-token/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.8k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>这里是在做项目的时候考虑到注册、登录以及用户验证之间的问题而涉及的。<a id="more"></a>在用户登录注册出于安全的考虑，需要遵循几个原则：</p>
<ol>
<li>在传输中不允许明文传输用户隐私数据</li>
<li>本地不允许明文存储用户隐私数据</li>
<li>服务器不允许明文保存用户隐私数据</li>
</ol>
<p>这里采用到的几种方法分别是加盐、HMAC+时间、jwt和cookie，下面分别来介绍：</p>
<h3 id="最简单的密码哈希"><a href="#最简单的密码哈希" class="headerlink" title="最简单的密码哈希"></a>最简单的密码哈希</h3><p>哈希算法是一个<strong>单向函数</strong>。它可以将任何大小的数据转化为定长的“指纹”，并且无法被反向计算。另外，即使数据源只改动了一丁点，哈希的结果也会完全不同（参考上面的例子）。这样的特性使得它非常适合用于保存密码，因为我们需要加密后的密码无法被解密，同时也能保证正确校验每个用户的密码。</p>
<p>在基于哈希加密的账户系统中，通常用户注册和认证的流程是这样的：</p>
<ol>
<li>用户注册一个帐号</li>
<li>密码经过哈希加密储存在数据库中。只要密码被写入磁盘，任何时候都不允许是明文</li>
<li>当用户登录的时候，从数据库取出已经加密的密码，和经过哈希的用户输入进行对比</li>
<li>如果哈希值相同，用户获得登入授权，否则，会被告知输入了无效的登录信息</li>
<li>每当有用户尝试登录，以上两步都会重复</li>
</ol>
<p>在第4步中，<strong>永远不要告诉用户到底是用户名错了，还是密码错了</strong>。只需要给出一个大概的提示，比如“无效的用户名或密码”。这可以防止攻击者在不知道密码的情况下，枚举出有效的用户名。</p>
<p>需要提到的是，用于保护密码的哈希函数和你在数据结构中学到的哈希函数是不同的。比如用于实现哈希表这之类数据结构的哈希函数，它们的目标是快速查找，而不是高安全性。只有<strong>加密哈希函数</strong>才能用于保护密码，例如SHA256，SHA512，RipeMD和WHIRLPOOL。</p>
<p>也许你很容易就认为只需要简单地执行一遍加密哈希函数，密码就能安全，那么你大错特错了。有太多的办法可以快速地把密码从简单哈希值中恢复出来，但也有很多比较容易实现的技术能使攻击者的效率大大降低。黑客的进步也在激励着这些技术的进步，比如这样一个网站：你可以提交一系列待破解的哈希值，并且在不到1秒的时间内得到了结果。显然，简单哈希加密并不能满足我们对安全性的需求。</p>
<h3 id="加盐"><a href="#加盐" class="headerlink" title="加盐"></a>加盐</h3><p>加盐就是在传输用户密码时候之前首先向服务器请求随机盐，这里的盐是通过 bcrypt.genSaltSync 生成的一段随机字符串，然后将盐与密码混合做HMAC，这里散列函数的选择为密钥扩展的慢哈希函数bcrypt，然后将得到的“密码”与当前的时间（精确到分钟）做一次SHA加密得到最终上传的“密码”</p>
<blockquote>
<p>hmac：就是计算一段字符串的哈希值时添加一个 key 混入其中</p>
<p>bcrypt：<strong>单向</strong>哈希加密算法，最后计算结果是 <code>bcrypt 版本号+saltRounds+salt+hash</code>。</p>
<ul>
<li>bcrypt 版本号默认 <code>$2a$</code></li>
<li>saltRounds：代表 hash 杂凑次数（越高越安全，可以理解为做多少次循环加密），范围 (4,31) 默认 10。</li>
<li>salt：随机盐，128 bits 随机字符串，22字符</li>
<li>hash：最终 hash 字符串</li>
</ul>
</blockquote>
<p>加盐：简单说就是将隐私数据与一段乱码混合编码，如果放在客户端源代码中只要对代码进行反编译就可以解码，并且如果一旦设定后修改代价大，即如果改动后服务端存放的还是之前的盐进行编码的结果。</p>
<p>HMAC：就是将盐放到了服务端，但这样还是有被截取盐的风险，解决方法是客户端拿到盐后进行本地持久化。但问题是注册时返回的（第一次）或者本地的盐还是有可能泄露，或者抓包可以通过 hmac 加密后的字符串进行登录</p>
<p>HMAC+时间：客户端和服务端无需通信进行加密的动态“种子”</p>
<h3 id="token"><a href="#token" class="headerlink" title="token"></a>token</h3><p>jwt token：JSON Web Tokens</p>
<p>类似 cookie，在客户端进行用户认证对象的存储。为了防止用户篡改数据，服务器在生成这个对象会加上签名，并且每个字段都会进行编码（base64）处理</p>
<p>jwt 分为三个部分（内部没有换行，用 <code>.</code> 分隔）：</p>
<ul>
<li>header （头部）：JSON 对象，描述 jwt 元数据（签名算法、令牌token类型）</li>
<li>payload （负载）：JSON 对象，实际传输数据，如签发人、过期时间、生效时间等</li>
<li>signature （签名）：对前两部分的签名，默认 sha 算法，秘钥只有服务器知道</li>
</ul>
<p>客户端收到 jwt 进行持久化，可以选择 cookie 或 localStrage，之后的每次请求都要带上这个 jwt：</p>
<ul>
<li>可以放到 cookie 中自动发送（不能跨域）</li>
<li>放到 http 请求头中 authorization 字段里</li>
</ul>
<h3 id="前端常用的编码和加密-js-库"><a href="#前端常用的编码和加密-js-库" class="headerlink" title="前端常用的编码和加密 js 库"></a>前端常用的编码和加密 js 库</h3><p>摘要和加密</p>
<ul>
<li>摘要是哈希值，用于验证数据完整性和唯一性，长度固定，即摘要不是原始数据加密后的密文，只是一个验证身份的令牌，无法通过摘要解密得到原始数据。</li>
<li>加密是通过加密算法将明文加密成密文，可以通过密钥和解密算法将密文还原为明文</li>
</ul>
<h4 id="编码"><a href="#编码" class="headerlink" title="编码"></a>编码</h4><ul>
<li><p>base64，数据编码方法，将二进制数据转换成64个可打印字符组成的序列，虽然可逆但编码方式是公开的。用于网络传输，在某些基于文本的协议中如果要传输图片或者文件，需要将二进制数据编码成文本格式。</p>
<p>js 库：<a href="https://www.npmjs.com/package/base64-js" target="_blank" rel="noopener">base64-js</a></p>
</li>
</ul>
<h4 id="加密"><a href="#加密" class="headerlink" title="加密"></a>加密</h4><ul>
<li><p>md5，摘要算法，也可以看做单向加密算法（不可逆即不能解密）。</p>
<p>可以将根据任意数据产生一个128位（16字节）的散列值</p>
<p>js库：<a href="https://www.npmjs.com/package/js-md5" target="_blank" rel="noopener">js-md5</a></p>
</li>
<li><p>sha，secure hash algorithm 安全散列算法，一般称 sha-1，对长度不超过 264 二进制位的消息产生 160 位消息摘要输出。也可以看做摘要算法。此算法基于 md5</p>
<p>js库： <a href="https://www.npmjs.com/package/js-sha1" target="_blank" rel="noopener">js-sha1</a></p>
</li>
<li><p>rsa：非对称秘钥加密</p>
<p>js 库： <a href="https://www.npmjs.com/package/encryptjs" target="_blank" rel="noopener">enctyptjs</a></p>
</li>
</ul>
<blockquote>
<p>参考</p>
<p><a href="https://www.iteye.com/blog/stark-summer-1313884" target="_blank" rel="noopener">数字签名算法 md5 和 sha-1 的比较</a></p>
<p><a href="https://juejin.im/post/6844903498329358349" target="_blank" rel="noopener">注册、登录和 token 安全之道</a></p>
<p><a href="https://www.liaoxuefeng.com/wiki/1016959663602400/1183198304823296" target="_blank" rel="noopener">hmac</a></p>
<p><a href="http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html" target="_blank" rel="noopener">阮一峰 token</a></p>
<p><a href="https://www.cnblogs.com/mmzs/p/10127332.html" target="_blank" rel="noopener">利用 sha-1 算法和 rsa 秘钥进行签名验证</a></p>
</blockquote>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/24/p2p-tong-xin-biao-zhun-xie-yi-stun/" rel="next" title="【转载】P2P通信标准协议-STUN">
                <i class="fa fa-chevron-left"></i> 【转载】P2P通信标准协议-STUN
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/26/p2p-tong-xin-biao-zhun-xie-yi-turn/" rel="prev" title="【转载】P2P通信标准协议-TURN">
                【转载】P2P通信标准协议-TURN <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">renhao</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">94</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#最简单的密码哈希"><span class="nav-number">1.</span> <span class="nav-text">最简单的密码哈希</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#加盐"><span class="nav-number">2.</span> <span class="nav-text">加盐</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#token"><span class="nav-number">3.</span> <span class="nav-text">token</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#前端常用的编码和加密-js-库"><span class="nav-number">4.</span> <span class="nav-text">前端常用的编码和加密 js 库</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#编码"><span class="nav-number">4.1.</span> <span class="nav-text">编码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#加密"><span class="nav-number">4.2.</span> <span class="nav-text">加密</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">renhao</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">265.9k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '2P1xqUWiCoNm14MH4yhURlJi-gzGzoHsz',
        appKey: 'uJN0uagHIVgXtBO1OuLV9Ban',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
